/*************************************************************************

    calc.c  5.01

*************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include "SlkAction.h"
#include "SlkError.h"
#include "SlkToken.h"
#include "SlkParse.h"

// -----------------------------------------------------------------------
// main for desk calculator
// -----------------------------------------------------------------------

#define HELP        1
#define DISPLAY     2

main ( int     argc,
       char  **argv )
{
    char      *p,
              *expr = NULL;
    int        options = 0;
    double     answer;
    SlkToken   peeker;
    SlkError   error;
    SlkAction  action;

    while ( --argc > 0 ) {                      // process command line options
        p = *++argv;
        switch ( *p ) {
            case '-':
                while ( *++p ) {
                    switch ( *p ) {
                        case 'd':
                            options |= DISPLAY;
                            break;
                        case 'h':
                        case '?':
                            options |= HELP;
                            break;
                        default:
                            fprintf (stderr, "Invalid option, %c\n", *p);
                    }
                }
                break;
            default:
                expr = p;
        }
    }
    printf ("DESK CALCULATOR: operators are *, /, +, -, ^  (calc -h for help)\n");
    if (options & HELP){
        printf (
            "Usage:  calc  [expression] [ options ]\n\n"
            "  -d    display parse derivation \n"
            "  -h    help \n"
            "\n"
            );
    }
    InitializePeeker ( &peeker, expr );
    InitializeError ( &error, &peeker );
    InitializeAction ( &action, options & DISPLAY, &peeker );

    if ( expr ) {
        SlkParse ( &action, &peeker, &error, 0 );
        printf ("answer = %f\n", action.answer );
        printf ("post order abstract syntax tree traversal:\n" );
        answer = post_order(&action);
        printf ("\nanswer = %f\n", answer);

        printf ("=====================\n" );
        printf ("show_parse_derivation\n" );
        printf ("=====================\n" );
        show_parse_derivation (&action);
        printf ("=====================\n" );
        printf ("show_tree\n" );
        printf ("=====================\n" );
        show_tree (&action);
        printf ("\nanswer = %.2f\n", answer);
    }

    return 0;
}
